import { defineStore } from "pinia";
import { store } from "@/stores";
import type { cacheType } from "../types";
import { constantMenus } from "@/router";
import { ascending, filterTree, filterNoPermissionTree } from "@/router/utils";

export const usePermissionStore = defineStore({
  id: "tc-permission",
  state: () => ({
    // 静态路由生成的菜单
    constantMenus,
    // 整体路由生成的菜单（静态、动态）
    wholeMenus: [],
    // 缓存页面keepAlive
    cachePageList: [],
    // 按钮权限 (Cup)
    permission: {},
  }),
  actions: {
    /** 组装整体路由生成的菜单 */
    handleWholeMenus(routes: any[]) {
      // NOTE：目前不需要根据角色过滤菜单
      this.wholeMenus = filterTree(
        ascending(constantMenus.filter((m) => m.name !== "home").concat(routes))
      );
    },
    cacheOperate({ mode, name }: cacheType) {
      switch (mode) {
        case "add":
          this.cachePageList.push(name);
          this.cachePageList = [...new Set(this.cachePageList)];
          break;
        case "delete":
          // eslint-disable-next-line no-case-declarations
          const delIndex = this.cachePageList.findIndex((v) => v === name);
          delIndex !== -1 && this.cachePageList.splice(delIndex, 1);
          break;
      }
    },
    /** 清空缓存页面 */
    clearAllCachePage() {
      this.wholeMenus = [];
      this.cachePageList = [];
    },
    /** 设置按钮权限 */
    setPermission(authButton) {
      const result: string[] = [];
      function getCode(list) {
        list.forEach((ele) => {
          if (typeof ele === "object") {
            const children = ele.children;
            const code = ele.code;
            if (children) {
              getCode(children);
            } else {
              result.push(code);
            }
          }
        });
      }
      getCode(authButton);
      this.permission = {};
      result.forEach((ele) => {
        this.permission[ele] = true;
      });
    },
  },
});

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
